import Taro, {Component,Config} from "@tarojs/taro";
import {View, Image, Text, ScrollView} from "@tarojs/components";
import {toJS} from 'mobx'
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime, pageSize, subtime} from '../../utils/common'

import './order.less'

// 我的订单
interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class Order extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    orderState:[
      {id:0, name:'全部'},
      {id:1, name:'待付款'},
      {id:2, name:'待发货'},
      {id:3, name:'待收货'},
      {id:4, name:'已完成'},
    ],
    currentState: 0,
    totalCount:0,
    items:[],
    pageIndex:1,
    pageSize,
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'我的订单' })
    this.getOrders()
  }

  config: Config = {
    navigationBarTitleText: '我的订单'
  }

  changeCurrentState(currentState:number) {
    this.setState({
      currentState,
      items: [],
      pageIndex: 1
    },() => {
      this.getOrders()
    })
  }

  getOrders() {
    let { PointMallStore } =  this.props.stores
    let { pageIndex,pageSize,currentState } = this.state
    PointMallStore.getOrders({
      formStatus:currentState===0?null:currentState,
      pageIndex,
      pageSize,
      callback: res => {
        res.items&&res.items.map(item => {
          let orderLimiTime = this.getLimitTime(item.creationTime)
          return item.orderLimiTime = orderLimiTime
        })
        if (pageIndex === 1) {
          this.setState({totalCount: toJS(res.totalCount), items: toJS(res.items)})
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }

  // 计算订单有效期倒计时(有效期为24小时)
  getLimitTime(time: string) {
    // 有效期减去现在时间就是订单剩余时间
    let now = new Date()
    let dayStamp = 24*60*60*1000 // 一天的时间戳(毫秒数)
    let orderTime = new Date(time).getTime() // 订单创建时间
    let orderLimitTime = orderTime+dayStamp // 订单有效期
    let nowTimeStamp = now.getTime() // 现在的时间戳
    let inteval = orderLimitTime-nowTimeStamp // 订单剩余时间
    let hoursTamp = 1000*60*60
    let hours = Math.floor(inteval/hoursTamp)
    let minStamp = inteval%hoursTamp
    let min = Math.floor(minStamp/(1000*60))
    if(hours<0) { return '订单已失效' }
    return `${hours}小时${min}分钟后订单将关闭`
  }

  // 取消订单
  cancelOrdedr(id: number) {
    if(!id) {getRuntime().showToast('参数错误~'); return;}
    Taro.showModal({
      title: '你确定要取消订单吗?',
      content:'',
      cancelText:'再想想',
      confirmText:'确认取消',
    })
      .then(res => {
        if (res.confirm) {
          let { PointMallStore } =  this.props.stores
          PointMallStore.cancelOrder({
            form: { id },
            callback: () => {
              getRuntime().showToast('取消订单成功~')
            }
          })
        }
      });
  }

  // 删除订单
  delOrder(id: number) {
    if(!id) {getRuntime().showToast('参数错误~'); return;}
    Taro.showModal({
      title: '你确定要删除订单吗?',
      content:'',
      cancelText:'再想想',
      confirmText:'确认删除',
    })
      .then(res => {
        if (res.confirm) {
          let { PointMallStore } =  this.props.stores
          PointMallStore.deleteOrder({
            form: { id },
            callback: () => {
              getRuntime().showToast('删除订单成功~')
            }
          })
        }
      });
  }

  // 确认收货
  confirmGet(id: number) {
    if(!id) {getRuntime().showToast('参数错误~'); return;}
    let { PointMallStore } = this.props.stores
    PointMallStore.confirmGet({
      form: { id },
      callback: () => {getRuntime().showToast('收货成功~')}
    })
  }

  // 再来一单
  againOrder(item: object) {
    if(!item.id) {getRuntime().showToast('参数错误~'); return;}
    //console.log(item)
    let userCart = {
      freight: item.freight,
      itemId: item.orderDetails[0]['itemId'],
      itemNum: item.orderDetails[0]['qty'],
      itemSignPrice: item.orderDetails[0]['price'],
      itemPrice: item.orderDetails[0]['totalPrice'],
      itemSpec: item.orderDetails[0]['spec'],
      name: item.orderDetails[0]['name'],
      picture: item.orderDetails[0]['picture'],
      publicDonations: item.gyMoney || 0,
      pointValue: item.pointValue || 0,
      specNo: '',
      specNoId: item.orderDetails[0]['itemSpecId']
    }
    //console.log(userCart)
    getRuntime().setStorage('userCart', userCart)
    getRuntime().navigateTo('/pages/mall/order_confirm?id='+item.orderDetails[0]['itemId'])
    /*let { PointMallStore } = this.props.stores
    PointMallStore.placeNewOrder({
      item.id,
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res,() => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
        })
      }
    })*/
  }

  // 立即支付
  pay(id: number) {
    if(!id) {getRuntime().showToast('参数错误~'); return;}
    let { PointMallStore } = this.props.stores
    PointMallStore.pay({
      form: {
        orderId: id,
        payType: '1',
        isPayPoints: false
      },
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res,() => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
        })
      }
    })
  }

  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getOrders()
      })
    }
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  render() {
    let { orderState,currentState,items } = this.state
    return (
      <View className='my-order-detail my-order'>
        <ScrollView className='scroll-view-nav' scrollX={true}>
          {
            orderState.map(item => {
              return(
                <View className={currentState===item.id?'scroll-item scroll-item-on':'scroll-item'} key={item.id}
                      onClick={this.changeCurrentState.bind(this,item.id)}
                >{item.name}<Text className='line' /></View>
              )
            })
          }
        </ScrollView>

        <View className='my-order-wrap'>
          {
            items.length>0&&
              items.map(item => {
                let tpl = null
                let tplCommon =
                  <View onClick={this.handelRouter.bind(this, '/pages/user/order_detail?id='+item.id)}>
                    <View className='time-status'>
                      <View className='list-info'>{subtime(item.creationTime)}</View>
                      <View className='list-title color-orange'>{item.statusView}</View>
                    </View>
                    <View className='order-spec'>
                      <View className='l'>
                        <Image className='img' src={item.orderDetails[0]['picture']} />
                        <View className='info'>
                          <View className='list-title'>{item.orderDetails[0]['name']}</View>
                          <View className='list-info'>
                            {/*<Text>5kg</Text>
                            <Text className='line'>|</Text>
                            <Text>盒装</Text>*/}
                            {item.orderDetails[0]['spec']}
                          </View>
                        </View>
                      </View>
                      <View className='r'>
                        <View className='list-price'>
                          <Text className='list-small'>￥</Text>{item.orderDetails[0]['totalPrice']}</View>
                        <View className='list-info' style={{textAlign:'right'}}>
                          <Text>x{item.orderDetails[0]['qty']}</Text>
                        </View>
                      </View>
                    </View>
                 </View>
                // 待付款
                if(item.status===1){
                    tpl =
                      <View className='order-item'>
                        { tplCommon }
                        <View className='line undelive'>
                          <View className='list-title'> </View>
                          <View className='money color-orange'><Text className='list-title'>共{item.orderDetails[0]['qty']}件商品 应付款：</Text><Text className='list-small'>￥</Text>{item.actualAmount}</View>
                        </View>
                      {/*  <View className='line'>
                          <View className='list-title'>订单金额</View>
                          <View className='money color-orange'><Text className='list-small'>￥</Text>{item.actualAmount}</View>
                        </View>*/}

                        <View className='line line2'>
                          <View className='list-desc l'>{item.orderLimiTime}</View>
                          <View className='r'>
                            <View className='btn' onClick={this.cancelOrdedr.bind(this,item.id)}>取消订单</View>
                            <View className='btn btn-submit' onClick={this.pay.bind(this,item.id)}>立即付款</View>
                          </View>
                        </View>
                      </View>
                }
                // 待发货
                if(item.status===2){
                  tpl =
                    <View className='order-item'>
                      { tplCommon }
                      <View className='line undelive'>
                        <View className='list-title'> </View>
                        <View className='money color-orange'><Text className='list-title'>共{item.orderDetails[0]['qty']}件商品 应付款：</Text><Text className='list-small'>￥</Text>{item.actualAmount}</View>
                      </View>
                    </View>
                }
                // 待收货
                if(item.status===3){
                  tpl =
                    <View className='order-item'>
                      { tplCommon }
                      <View className='line'>
                        <View className='list-title'>订单金额</View>
                        <View className='money color-orange'><Text className='list-small'>￥</Text>{item.actualAmount}</View>
                      </View>

                      <View className='line line2'>
                        <View className='list-desc color-blue'>运单号：{item.shippingNo}</View>
                        <View className='btn' onClick={this.confirmGet.bind(this,item.id)}>确认收货</View>
                      </View>
                    </View>
                }
                // 待评价
                if(item.status===4){
                  tpl =
                    <View className='order-item'>
                      { tplCommon }
                      <View className='line'>
                        <View className='list-title'>订单金额</View>
                        <View className='money color-orange'><Text className='list-small'>￥</Text>{item.actualAmount}</View>
                      </View>

                      <View className='line line2'>
                        <View className='l' />
                        <View className='r'>
                          <View className='btn' onClick={this.delOrder.bind(this,item.id)}>删除订单</View>
                          <View className='btn btn-active' onClick={this.againOrder.bind(this,item)}>再次购买</View>
                        </View>
                      </View>
                    </View>
                }
                return tpl
              })
          }
          {items.length<=0&& <View className='from-footer'>你还没有订单哦~</View>}
        </View>

      </View>
    )
  }
}

export default Order
